package com.lwl.Algorithmic_data_structure.堆与堆排序.加强堆;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class 合并区间 {
    class Line{
        int left;
        int right;

        public Line(int left, int right) {
            this.left = left;
            this.right = right;
        }
    }
    public int[][] merge(int[][] intervals) {
        List<Line> allLine = new ArrayList<>();
        //起点相同，就按终点从大到小pai
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] == o2[0] ? o2[1] - o1[1] : o1[0] - o2[0];
            }
        });
        int maxSide = intervals[0][1];
        allLine.add(new Line(intervals[0][0],intervals[0][1]));
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] <= maxSide){
                maxSide = Math.max(intervals[i][1],maxSide);
                allLine.get(allLine.size()-1).right = maxSide;
            }else{
                allLine.add(new Line(intervals[i][0],intervals[i][1]));
                maxSide = intervals[i][1];
            }
        }
        int[][] res = new int[allLine.size()][2];
        for (int i = 0; i < res.length; i++) {
            res[i][0] = allLine.get(i).left;
            res[i][1] = allLine.get(i).right;
        }
        return res;
    }
    @Test
    public void test(){
        int[][] merge = merge(new int[][]{
                {1, 3},
                {2, 6},
                {8, 10},
                {15, 18}
        });
        for (int i = 0; i < merge.length; i++) {
            System.out.println(merge[i][0] + " " + merge[i][1]);
        }
    }
}
